//
//  DropImageView.m
//  SohoNaru
//
//  Created by pnpWhite on 13. 7. 3..
//  Copyright (c) 2013년 ladaka Inc. All rights reserved.
//

#import "DropImageView.h"
#import "WUtil.h"

@implementation DropImageView
@synthesize imgPath = _imgPath;
@synthesize delegate = _delegate;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}


/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect
 {
 // Drawing code
 }
 */


- (void) awakeFromNib {
    self.imgPath = @"";
    self.vMain = nil;
    self.svParent = nil;
    self.image = nil;
    
    self.isTouch = NO;
    _isScroll = YES;
    self.backgroundColor = [UIColor clearColor];
    
    self.ivMain = [[UIImageView alloc] initWithFrame:CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, self.frame.size.height)];
    self.ivMain.backgroundColor = [UIColor clearColor];
    
    if (self.tag == 0) {
        self.ivDrop = [[UIImageView alloc] initWithFrame:CGRectMake(self.frame.size.width, self.frame.size.height, self.frame.size.width/2, self.frame.size.height/2)];
    }
    else {
        self.ivDrop = [[UIImageView alloc] initWithFrame:CGRectMake(self.frame.size.width, self.frame.size.height, self.frame.size.width, self.frame.size.height)];
    }
    
    
    self.ivDrop.hidden = YES;
    
    NSLog(@"self.frame.size:%f, %f", self.frame.size.width, self.frame.size.height);
    [self addSubview:self.ivDrop];
    [self addSubview:self.ivMain];
}

- (void) setMainImgPath:(NSString *)imgPath {
    _imgPath = imgPath;
    if ([_imgPath isEqualToString:@""] || _imgPath == nil) {
        self.ivMain.image = nil;
    }
    else {

        UIImage *img = [UIImage imageWithContentsOfFile:_imgPath];
        CGFloat heightPercentage = self.superview.frame.size.height / img.size.height;
        CGFloat widthPercentage = self.superview.frame.size.width / img.size.width;
        
//        NSLog(@"====imgFrameSize:%f, %f", img.size.width, img.size.height);
//        NSLog(@"====frameSize:%f, %f", self.frame.size.width, self.frame.size.height);
//        NSLog(@"====superviewSize:%f, %f", self.superview.frame.size.width, self.superview.frame.size.height);
        
        if (img.size.width > img.size.height) {
            if(img.size.width/img.size.height > self.superview.frame.size.width/self.superview.frame.size.height){
                img = [WUtil resizeWithImage:img scaledToSize:CGSizeMake(img.size.width*heightPercentage, img.size.height*heightPercentage)];
            }else{
                img = [WUtil resizeWithImage:img scaledToSize:CGSizeMake(img.size.width*widthPercentage, img.size.height*widthPercentage)];
            }
        } else if(img.size.width < img.size.height) {
            if(img.size.height/img.size.width < self.superview.frame.size.height/self.superview.frame.size.width){
                img = [WUtil resizeWithImage:img scaledToSize:CGSizeMake(img.size.width*heightPercentage, img.size.height*heightPercentage)];
            }else{
                img = [WUtil resizeWithImage:img scaledToSize:CGSizeMake(img.size.width*widthPercentage, img.size.height*widthPercentage)];
        }
        }

        // 정사이즈 이미지 처리
        if (img.size.width == img.size.height){
            if(self.superview.frame.size.width < self.superview.frame.size.height){
                img = [WUtil resizeWithImage:img scaledToSize:CGSizeMake(img.size.width*heightPercentage, img.size.height*heightPercentage)];
            }
            else {
                img = [WUtil resizeWithImage:img scaledToSize:CGSizeMake(img.size.width*widthPercentage, img.size.height*widthPercentage)];
            }
        }
        
        self.ivMain.image = img;
            
        self.frame = CGRectMake(0, 0, img.size.width, img.size.height);
        self.ivMain.frame = CGRectMake(0, 0, img.size.width, img.size.height);
        self.ivMain.contentMode = UIViewContentModeScaleAspectFill;
        
        NSLog(@"imgSize:%f, %f", img.size.width, img.size.height);
    }
}

- (void) setImgPath:(NSString *)imgPath {
    _imgPath = imgPath;
    if ([_imgPath isEqualToString:@""] || _imgPath == nil) {
        self.ivMain.image = nil;
    }
    else {
        UIImage *img = [UIImage imageWithContentsOfFile:_imgPath];
         if(img.size.width > 640)
             img = [WUtil resizeWithImage:img scaledToSize:CGSizeMake(img.size.width/3, img.size.height/3)];
        self.ivMain.image = img;
    }
}

- (NSString *) imgPath {
    return _imgPath;
}


- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesCancelled:touches withEvent:event];
    
    self.multipleTouchEnabled = YES;
    
    if (YES == _isScroll) {
        UIImage *img = [[UIImage alloc] initWithContentsOfFile:self.imgPath];
         if(img.size.width > 640)
             img = [WUtil resizeWithImage:img scaledToSize:CGSizeMake(img.size.width/3, img.size.height/3)];
        
        if (img == nil || [self.imgPath isEqualToString:@""]) {
            return;
        }
        _originalPoint = self.ivDrop.center;
        
        self.svParent.scrollEnabled = NO;

        self.ivDrop.hidden = NO;
        self.ivDrop.alpha = 0.7;
        self.ivDrop.image = img;
        
        
        CGPoint point = CGPointZero;
        
        //        point = [self.ivDrop convertPoint:[[touches anyObject] locationInView:self.ivDrop] toView:self.vMain];
        
        point = [self.vMain convertPoint:[[touches anyObject] locationInView:self.vMain] toView:self.vMain];
        
        
        self.ivDrop.center = point;
        _originalOutSidePoint = point;
        
        [self.vMain addSubview:self.ivDrop];
        [self.vMain bringSubviewToFront:self.ivDrop];
        
        
        for (UIView *subView in self.svParent.subviews) {
            for (UIView *view in subView.subviews) {
                for (UITapGestureRecognizer *geture in [view gestureRecognizers]) {
                    [geture setEnabled:NO];
                }
            }
        }
        
        UITouch *touch = [touches anyObject];
        NSLog(@"touch:%i", touch.phase);
        
        if (touch.phase == UITouchPhaseStationary) {
            NSLog(@"UITouchPhaseStationary");
            [self performSelector:@selector(touchesEnded:withEvent:) withObject:nil afterDelay:0.3];
        }
        
        
        if ([self.delegate respondsToSelector:@selector(didMainImgTouchDown:)]) {
            [self.delegate didMainImgTouchDown:self.ivDrop];
        }
        
        
        _isScroll = NO;
        

    }
}

- (void) stopTapGesture {
    self.ivDrop.hidden = YES;
}


- (void) touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesCancelled:touches withEvent:event];
    
    UITouch *touch = [touches anyObject];
    if (touch.phase == UITouchPhaseCancelled) {
        [self performSelectorOnMainThread:@selector(touchesEnded:withEvent:) withObject:nil waitUntilDone:NO];
    }
}


- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesMoved:touches withEvent:event];
    
    self.isTouch = NO;
    [UIView beginAnimations:@"mainImgDropStart" context:nil];
    [UIView setAnimationDuration:.001];
    [UIView setAnimationBeginsFromCurrentState:YES];
    
    UITouch *touch = [touches anyObject];
    self.ivDrop.center = [touch locationInView:self.vMain];
    
    [UIView commitAnimations];
    
    if ([self.delegate respondsToSelector:@selector(didTrayInside:imgPath:touching:tag:)]) {
        
        [self.delegate didTrayInside:self.ivDrop imgPath:self.imgPath touching:NO tag:self.tag];
    }
}



- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesEnded:touches withEvent:event];
    
    self.ivDrop.hidden = YES;
    [self bringSubviewToFront:self.vMain];
    
    self.isTouch = YES;
    [UIView beginAnimations:@"mainImgDropEnd" context:nil];
    [UIView setAnimationDuration:.4];
    [UIView setAnimationBeginsFromCurrentState:YES];
    
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(didStop:finished:context:)];
    [UIView commitAnimations];
    self.svParent.scrollEnabled = YES;
    
    for (UIView *subView in self.svParent.subviews) {
        for (UIView *view in subView.subviews) {
            for (UITapGestureRecognizer *geture in [view gestureRecognizers]) {
                [geture setEnabled:YES];
            }
        }
    }
    
    
    if ([self.delegate respondsToSelector:@selector(didMainImgTouchUp:)]) {
        [self.delegate didMainImgTouchUp:self];
    }
    
    if ([self.delegate respondsToSelector:@selector(didTrayInside:imgPath:touching:tag:)]) {
        NSLog(@"dropImage Tag:%i", self.tag);
        self.isTouch = NO;
        [self.delegate didTrayInside:self.ivDrop imgPath:self.imgPath touching:YES tag:self.tag];
    }
    
    self.ivDrop.center = _originalPoint;
}


- (void) didStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
    if ([animationID isEqualToString:@"mainImgDropEnd"] && finished) {
        self.ivDrop.hidden = YES;
        [self.svParent addSubview:self.ivDrop];
        _isScroll = YES;
    }
}


@end
